﻿using System.ComponentModel;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.DataEntity;
using Kingdee.BOS.Util;

namespace Caraya.MFG.BusinessPlugIn
{
    [Description("串口通信调试插件"), HotUpdate]
    public class SerialPortDebug : AbstractDynamicFormPlugIn
    {
        public override void ButtonClick(ButtonClickEventArgs e)
        {
            base.ButtonClick(e);
            if (e.Key == "F_CARA_BUTTON1")//打开串口
            {
                var cfg = new KDSerialPortConfig();
                cfg.PortName = "COM9";
                cfg.Rate = 9600;
                cfg.Parity = 0;
                cfg.StopBits = 1;
                cfg.Bits = 8;
                cfg.Timeout = -1;
                cfg.EncodingName = "ASCII";
                cfg.RecDataEndingChars = "FF";
                this.View.GetControl<SerialPortControl>("F_CARA_SerialPortCtrl").Init(cfg);
            }
            if (e.Key == "F_CARA_BUTTON2")//关闭串口
            {
                this.View.GetControl<SerialPortControl>("F_CARA_SerialPortCtrl").Close();
            }
            if (e.Key == "fc")//允许串口控件反馈回调CustomEvents事件
            {
                this.View.GetControl<SerialPortControl>("F_CARA_SerialPortCtrl").SetAllowFireEvtBack(true);
            }
            if (e.Key == "fb")//关闭串口控件反馈回调CustomEvents事件
            {
                this.View.GetControl<SerialPortControl>("F_CARA_SerialPortCtrl").SetAllowFireEvtBack(false);
            }
        }

        public override void PortDataReceived(KDSerialPortEventArgs e)
        {
            // e2003412012b02000ff8adff
            base.PortDataReceived(e);
            if (e.Value != null)
            {
                if (e.Value.ToString().Length >= 28)
                {
                    var sn = e.Value.ToString().Substring(4, 24);
                    this.View.Model.SetValue("FCloseReason", sn);
                }
            }

        }
    }
}
